package allwe.lock;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {

    private static ReentrantLock reentrantLock = new ReentrantLock();

    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(ReentrantLockTest::incr);
        Thread t2 = new Thread(ReentrantLockTest::incr);
        Thread t3 = new Thread(ReentrantLockTest::incr);

        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();

        System.out.println(count);
    }

    private static void incr() {
        try {
            reentrantLock.lock();
            for (int i = 0; i < 10000; i++) {
                count++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            reentrantLock.unlock(); // 手动释放锁
        }
    }
}
